package com.example.test.util;


import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * @Author 林文峰
 * @Date 2020/7/1 0001 14:33
 */
public class Html2PDF {

	public static void main(String[] args) {
		try {
			htmlTOPDF();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
//	public static String readHtml(){
//		StringBuilder strline = new StringBuilder("");
//		File fin = new File("F:\\下载位置\\新建文本.html");
//		try (RandomAccessFile accessFile = new RandomAccessFile(fin, "r");
//			 FileChannel fcin = accessFile.getChannel();
//		){
//			Charset charset = Charset.forName("UTF-8");
//			int bufSize = 100000;
//			ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);
//			String enterStr = "\n";
//			byte[] bs = new byte[bufSize];
//
//			StringBuilder strBuf = new StringBuilder("");
//			while (fcin.read(rBuffer) != -1) {
//				int rSize = rBuffer.position();
//				rBuffer.rewind();
//				rBuffer.get(bs);
//				rBuffer.clear();
//				String tempString = new String(bs, 0, rSize,charset);
//				tempString = tempString.replaceAll("\r", "");
//
//				int fromIndex = 0;
//				int endIndex = 0;
//				while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
//					String line = tempString.substring(fromIndex, endIndex);
//					line = strBuf.toString() + line;
//					strline.append(line.trim());
//
//					strBuf.delete(0, strBuf.length());
//					fromIndex = endIndex + 1;
//				}
//				if (rSize > tempString.length()) {
//					strline.append(tempString.substring(fromIndex, tempString.length()));
//					strBuf.append(tempString.substring(fromIndex, tempString.length()));
//				} else {
//					strline.append(tempString.substring(fromIndex, rSize));
//					strBuf.append(tempString.substring(fromIndex, rSize));
//				}
//			}
//			System.out.println(strline.toString().replaceAll("\"", "'"));
//		} catch (Exception e) {
//			return null;
//		}
//		return strline.toString();
//	}
	
	public static void htmlTOPDF() throws IOException, DocumentException {
		InputStream ins = null;
		StringBuilder content = new StringBuilder();
//		StringBuilder result = new StringBuilder();
////		File file = new File("F:\\下载位置\\test1.html");
		try {
			int len = 0;
			//Html文件转为StringBuilder
			ins = new FileInputStream("F:\\下载位置\\新建文本.html");
			byte[] bytes = new byte[4096];
			while((len = ins.read(bytes)) != -1){
				content.append(new String(bytes,0,len));
			}
			ins.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String htmlString = content.toString();
//		String ="";
//		String s = readHtml();
		htmlString = htmlString
				.replaceAll("&omega;", "ω")
				.replaceAll("&pi","π")
				.replaceAll("&deg;","°")
				.replaceAll("&isin;","∈")
				.replaceAll("&alpha;","α")
				.replaceAll("&bull;","•");
//				.replaceAll("text-align:center","text-align:left");
//		if (htmlString.contains("font-family")){
//			htmlString = htmlString.replace("font-family:'Calibri';", "font-family:'SimSun';");    //注意这里为啥要写这个，主要是替换成这样的字体，如果不设置中文有可能显示不出来。
//		}else{
			htmlString = htmlString.replaceAll("<style>", 
					"<style>body{font-family:SimSun;font-size:14px;}@page{size : 300mm 200mm;}")
					.replaceAll("font-family:'Times New Roman'","font-family:'SimSun'")
					.replaceAll("font-family:'Cambria Math'","font-family:'SimSun'")
					.replaceAll("font-family:'Calibri'","font-family:'SimSun'");
//		}
		
		OutputStream os = new FileOutputStream("G:\\上传测试\\in.pdf");    //生成PDF文件的路径
		ITextRenderer renderer = new ITextRenderer();
		renderer.getSharedContext();
		renderer.setDocumentFromString(htmlString);
		ITextFontResolver font = renderer.getFontResolver();
		font.addFont("F:\\下载位置\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//添加中文识别，这里是设置的宋体，Linux下要换成对应的字体
		System.out.println(htmlString);
		renderer.layout();
		renderer.createPDF(os);
		renderer.finishPDF();
		os.close();
	}
}
